const BaseHandler     = require('../base-handler');
const HTTP_VERBS      = require('../../../constants').HTTP_VERBS;

class SettingsProfileHandler extends BaseHandler {

    get pattern() {
        return "/settings/profile";
    }

    doGET(request, response){
        if (!request.session.user.authenticated) {
            response.redirect('/login');
        } else {
            var userId = request.session.user.id;
            this.Controller.getUserProfile(userId, (result) => {
                response.render('console/user_info', {
                    user: request.session.user,
                    data: result
                })
            });
        }
    }

    doPOST(request, response) {
        if (!request.session.user.authenticated) {
            response.json({
                success: false,
                error: '非法操作!'
            });
        } else {
            var me = this;
            request.body.id = request.session.user.id;
            this.Controller.updateUserProfile(request.body, function (result) {
                if(result.success){
                    request.body.name && (request.session.user.name = request.body.name);
                    request.body.profile_image && (request.session.user.profile_image = me.Controller.getCDNImageURL(request.body.profile_image));
                    
                    response.end(JSON.stringify(result));
                } else {
                    response.end(JSON.stringify(result))
                }
            });
        }
    }

    setup() {
        this.registerVerb(HTTP_VERBS.POST, this.doPOST);
        this.registerVerb(HTTP_VERBS.GET, this.doGET);
    }
}

module.exports = SettingsProfileHandler;